package com.hc.wego.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hc.wego.bean.PageBean;
import com.hc.wego.domain.query.UserQuery;
import com.hc.wego.utils.CollectionUtil;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hc.wego.mapper.UserMapper;
import com.hc.wego.domain.entity.User;
import com.hc.wego.service.UserService;

import java.time.LocalDate;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

    @Override
    public PageBean<User> getPage(UserQuery query) {
        if (query == null) {
            throw new IllegalArgumentException("查询参数不能为空");
        }

        final Long pageNum = query.getPageNum();
        final Long pageSize = query.getPageSize();
        IPage<User> page = new Page<>(pageNum, pageSize);

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        final List<String> columns = query.getColumns();
        if (CollectionUtil.isNotEmpty(columns)) {
            queryWrapper.select(columns);
        }

        final String nickname = query.getNickname();
        if (nickname != null) {
            queryWrapper.like("nickname", nickname);
        }
        final Boolean gender = query.getGender();
        if (gender != null) {
            queryWrapper.eq("gender", gender);
        }
        final LocalDate[] birth = query.getBirth();
        if (birth != null && birth.length == 2) {
            queryWrapper.between("birth", birth[0], birth[1]);
        }
        final String email = query.getEmail();
        if (email != null) {
            queryWrapper.like("email", email);
        }
        final String phone = query.getPhone();
        if (phone != null) {
            queryWrapper.like("phone", phone);
        }
        final String account = query.getAccount();
        if (account != null) {
            queryWrapper.like("account", account);
        }
        final Integer credit = query.getCredit();
        if (credit != null) {
            queryWrapper.ge("credit", credit);
        }
        final Integer level = query.getLevel();
        if (level != null) {
            queryWrapper.ge("level", level);
        }
        final String info = query.getInfo();
        if (info != null) {
            queryWrapper.like("info", info);
        }
        final Boolean admin = query.getAdmin();
        if (admin != null) {
            queryWrapper.eq("admin", admin);
        }
        final Integer state = query.getState();
        if (state != null) {
            queryWrapper.eq("state", state);
        }

        this.page(page, queryWrapper);

        return PageBean.page2pageBean(page);
    }
}
